import React, { useState, useRef, useEffect } from 'react'
import { 
  Play, 
  Square, 
  Brain, 
  Wrench, 
  CheckCircle, 
  XCircle, 
  AlertCircle,
  ExternalLink,
  Copy,
  Trash2,
  Settings,
  FileText
} from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism'
import toast from 'react-hot-toast'
import { useWebSocket } from '../hooks/useWebSocket'
import { executionApi, configApi } from '../services/api'
import { cn } from '../utils/cn'

const ExecutionMonitor = ({ selectedItem, onRunStart, currentRunId }) => {
  const [isRunning, setIsRunning] = useState(false)
  const [runConfig, setRunConfig] = useState({})
  const [showConfigModal, setShowConfigModal] = useState(false)
  const messagesEndRef = useRef(null)
  
  const { 
    messages, 
    connectionStatus, 
    isComplete, 
    reportLinks, 
    clearMessages 
  } = useWebSocket(currentRunId)

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  // 处理运行状态变化
  useEffect(() => {
    if (isComplete) {
      setIsRunning(false)
    }
  }, [isComplete])

  const handleStartExecution = async () => {
    if (!selectedItem) {
      toast.error('请先选择要执行的任务或套件')
      return
    }

    try {
      setIsRunning(true)
      clearMessages()
      
      const apiCall = selectedItem.type === 'task' 
        ? () => executionApi.runTask(selectedItem.filename, runConfig)
        : () => executionApi.runSuite(selectedItem.filename, runConfig)
      
      const response = await apiCall()
      const runId = response.data.run_id
      
      onRunStart(runId)
      toast.success(`开始执行${selectedItem.type === 'task' ? '任务' : '套件'}: ${selectedItem.name}`)
      
    } catch (error) {
      setIsRunning(false)
      console.error('执行失败:', error)
      toast.error(`执行失败: ${error.response?.data?.detail || error.message}`)
    }
  }

  const handleStopExecution = () => {
    setIsRunning(false)
    toast.info('已请求停止执行')
  }

  const getMessageIcon = (type) => {
    switch (type) {
      case 'planner_thinking':
        return <Brain className="w-4 h-4 text-purple-500" />
      case 'tool_execution':
        return <Wrench className="w-4 h-4 text-blue-500" />
      case 'tool_result':
        return <CheckCircle className="w-4 h-4 text-green-500" />
      case 'error':
        return <XCircle className="w-4 h-4 text-red-500" />
      case 'success':
        return <CheckCircle className="w-4 h-4 text-green-500" />
      case 'completion':
        return <CheckCircle className="w-4 h-4 text-green-600" />
      case 'system':
        return <AlertCircle className="w-4 h-4 text-blue-600" />
      default:
        return <AlertCircle className="w-4 h-4 text-gray-500" />
    }
  }

  const getMessageBadgeColor = (type) => {
    switch (type) {
      case 'planner_thinking':
        return 'bg-purple-100 text-purple-800'
      case 'tool_execution':
        return 'bg-blue-100 text-blue-800'
      case 'tool_result':
        return 'bg-green-100 text-green-800'
      case 'error':
        return 'bg-red-100 text-red-800'
      case 'success':
        return 'bg-green-100 text-green-800'
      case 'completion':
        return 'bg-green-100 text-green-800'
      case 'system':
        return 'bg-blue-100 text-blue-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const formatTimestamp = (timestamp) => {
    return new Date(timestamp).toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3
    })
  }

  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text)
    toast.success('已复制到剪贴板')
  }

  const openReport = async (type) => {
    try {
      const apiCall = type === 'report' 
        ? () => executionApi.getReportLink(currentRunId)
        : () => executionApi.getPlaybackLink(currentRunId)
      
      const response = await apiCall()
      const urlKey = type === 'report' ? 'report_url' : 'playback_url'


      const relativePath = response.data[urlKey]
      
      if (relativePath) {
        const fullUrl = window.location.origin + relativePath
        window.open(fullUrl, '_blank')
      } else {
        toast.error('报告链接获取失败')
      }
      
    } catch (error) {
      console.error(`获取${type === 'report' ? '测试报告' : '回放报告'}链接失败:`, error)
      toast.error(`无法打开${type === 'report' ? '测试报告' : '回放报告'}`)
    }
  }

  const ConfigModal = () => (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
      onClick={() => setShowConfigModal(false)}
    >
      <motion.div
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        exit={{ scale: 0.95, opacity: 0 }}
        className="bg-white rounded-lg p-6 w-96 max-w-[90vw]"
        onClick={e => e.stopPropagation()}
      >
        <h3 className="text-lg font-semibold mb-4">运行时配置</h3>
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              OPENAI_API_KEY
            </label>
            <input
              type="password"
              className="input w-full"
              placeholder="留空使用系统默认配置"
              value={runConfig.OPENAI_API_KEY || ''}
              onChange={e => setRunConfig(prev => ({ ...prev, OPENAI_API_KEY: e.target.value }))}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              MIDSCENE_MODEL_NAME
            </label>
            <input
              type="text"
              className="input w-full"
              placeholder="如: google/gemini-2.5-flash-preview"
              value={runConfig.MIDSCENE_MODEL_NAME || ''}
              onChange={e => setRunConfig(prev => ({ ...prev, MIDSCENE_MODEL_NAME: e.target.value }))}
            />
          </div>
        </div>
        <div className="flex justify-end space-x-3 mt-6">
          <button
            onClick={() => setShowConfigModal(false)}
            className="btn-secondary"
          >
            取消
          </button>
          <button
            onClick={() => setShowConfigModal(false)}
            className="btn-primary"
          >
            确定
          </button>
        </div>
      </motion.div>
    </motion.div>
  )

  return (
    <div className="h-full flex flex-col">
      {/* 控制面板 */}
      <div className="p-6 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-xl font-semibold text-gray-900">执行监控</h2>
            <p className="text-sm text-gray-500 mt-1">
              实时监控AI Agent的思考和执行过程
            </p>
          </div>
          
          <div className="flex items-center space-x-3">
            {/* 配置按钮 */}
            <button
              onClick={() => setShowConfigModal(true)}
              className="btn-ghost"
              title="运行时配置"
            >
              <Settings className="w-4 h-4" />
            </button>

            {/* 清空日志 */}
            <button
              onClick={clearMessages}
              className="btn-ghost"
              title="清空日志"
            >
              <Trash2 className="w-4 h-4" />
            </button>

            {/* 开始/停止按钮 */}
            {!isRunning ? (
              <button
                onClick={handleStartExecution}
                disabled={!selectedItem}
                className="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Play className="w-4 h-4 mr-2" />
                开始执行
              </button>
            ) : (
              <button
                onClick={handleStopExecution}
                className="bg-red-600 text-white hover:bg-red-700 btn"
              >
                <Square className="w-4 h-4 mr-2" />
                停止执行
              </button>
            )}
          </div>
        </div>

        {/* 状态栏 */}
        <div className="mt-4 flex items-center justify-between">
          <div className="flex items-center space-x-4">
            {selectedItem ? (
              <div className="flex items-center space-x-2">
                <div className={cn(
                  "w-3 h-3 rounded-full",
                  selectedItem.type === 'task' ? "bg-blue-500" : "bg-green-500"
                )} />
                <span className="text-sm font-medium text-gray-900">
                  {selectedItem.name}
                </span>
                <span className="text-xs text-gray-500">
                  ({selectedItem.type === 'task' ? '任务' : '套件'})
                </span>
              </div>
            ) : (
              <span className="text-sm text-gray-500">请选择要执行的任务或套件</span>
            )}
          </div>

          <div className="flex items-center space-x-4">
            {/* 连接状态 */}
            <div className="flex items-center space-x-2">
              <div className={cn(
                "w-2 h-2 rounded-full",
                connectionStatus === 'connected' ? "bg-green-500" :
                connectionStatus === 'connecting' ? "bg-yellow-500 animate-pulse" :
                connectionStatus === 'completed' ? "bg-blue-500" :
                "bg-gray-400"
              )} />
              <span className="text-sm text-gray-600">
                {connectionStatus === 'connected' ? '已连接' :
                 connectionStatus === 'connecting' ? '连接中' :
                 connectionStatus === 'completed' ? '已完成' :
                 '未连接'}
              </span>
            </div>
          </div>
        </div>
      </div>

      {/* 消息日志 */}
      <div className="flex-1 overflow-hidden">
        <div className="h-full overflow-y-auto scrollbar-thin p-6">
          {messages.length === 0 ? (
            <div className="h-full flex items-center justify-center">
              <div className="text-center">
                <Brain className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                <h3 className="text-lg font-medium text-gray-500 mb-2">
                  等待执行开始
                </h3>
                <p className="text-sm text-gray-400 max-w-md">
                  选择一个任务或套件，然后点击"开始执行"，您将看到AI Agent的完整思考和执行过程
                </p>
              </div>
            </div>
          ) : (
            <div className="space-y-4">
              <AnimatePresence>
                {messages.map((message) => (
                  <motion.div
                    key={message.id}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="group"
                  >
                    <div className="flex items-start space-x-3">
                      <div className="flex-shrink-0 mt-1">
                        {getMessageIcon(message.type)}
                      </div>
                      
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center space-x-2 mb-1">
                          <span className={cn("badge", getMessageBadgeColor(message.type))}>
                            {message.log_type || message.type}
                          </span>
                          <span className="text-xs text-gray-500">
                            {formatTimestamp(message.timestamp)}
                          </span>
                          {message.extracted_info?.tool_name && (
                            <span className="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded">
                              {message.extracted_info.tool_name}
                            </span>
                          )}
                        </div>
                        
                        <div className="bg-gray-50 rounded-lg p-3 relative">
                          <div className="text-sm text-gray-900 whitespace-pre-wrap font-mono">
                            {message.content}
                          </div>
                          
                          <button
                            onClick={() => copyToClipboard(message.content)}
                            className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-gray-200 rounded"
                            title="复制内容"
                          >
                            <Copy className="w-3 h-3 text-gray-500" />
                          </button>
                        </div>

                        {/* 显示提取的信息 */}
                        {message.extracted_info && Object.keys(message.extracted_info).length > 0 && (
                          <div className="mt-2 text-xs">
                            <SyntaxHighlighter
                              language="json"
                              style={tomorrow}
                              customStyle={{
                                fontSize: '11px',
                                padding: '8px',
                                borderRadius: '6px',
                                margin: 0
                              }}
                            >
                              {JSON.stringify(message.extracted_info, null, 2)}
                            </SyntaxHighlighter>
                          </div>
                        )}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </AnimatePresence>

              {/* 执行完成后的报告区域 */}
              {isComplete && currentRunId && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="mt-6 p-6 bg-gradient-to-r from-green-50 to-blue-50 border border-green-200 rounded-lg"
                >
                  <div className="text-center">
                    <div className="flex items-center justify-center mb-4">
                      <CheckCircle className="w-12 h-12 text-green-500" />
                    </div>
                    <h3 className="text-lg font-semibold text-gray-900 mb-2">
                      🎉 测试执行完成！
                    </h3>
                    <p className="text-sm text-gray-600 mb-6">
                      测试已成功完成，您可以查看详细的测试报告和执行回放
                    </p>
                    
                    <div className="flex items-center justify-center space-x-4">
                      <button
                        onClick={() => openReport('report')}
                        className="inline-flex items-center px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors shadow-md hover:shadow-lg"
                      >
                        <FileText className="w-5 h-5 mr-2" />
                        查看测试报告
                        <ExternalLink className="w-4 h-4 ml-2" />
                      </button>
                      
                      <button
                        onClick={() => openReport('playback')}
                        className="inline-flex items-center px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors shadow-md hover:shadow-lg"
                      >
                        <Play className="w-5 h-5 mr-2" />
                        查看执行回放
                        <ExternalLink className="w-4 h-4 ml-2" />
                      </button>
                    </div>
                    
                    <div className="mt-4 text-xs text-gray-500">
                      报告将在新窗口中打开
                    </div>
                  </div>
                </motion.div>
              )}

              <div ref={messagesEndRef} />
            </div>
          )}
        </div>
      </div>

      {/* 配置模态框 */}
      <AnimatePresence>
        {showConfigModal && <ConfigModal />}
      </AnimatePresence>
    </div>
  )
}

export default ExecutionMonitor
